import utils from "../../common/utils/utils";
import request from "../../common/utils/request";
import * as storage from "../../common/utils/storage";
import router from "../../router/index.js";
import { nextTick } from "vue";
import store from "../index.js";
import { setConfige } from '@/common/utils/atherUtils.js'

const user = {
  state: {
    lang: "zh_CN", // 当前语言
    orgId: storage.getOrgId(), // org_id
    configInfo: {},
    userInfo: storage.getUserInfo(),
    token: storage.getToken(),
    teamId: storage.getCurrentTeam(), // 团队id
    village: storage.getVillageInfo(),
    inviteCode: "",
    upload_path: "", //oss上传地址
    uploadProgress: [],
    cos_progressList: [],
    updataList: [],
    DelupData: [],
    uploadfailed: [],
    userType: 1, //
    aiConfig: null,
    sceneApps: {},
    ua_source: "",
    menu_permission: storage.getMenuPermission(),
    // 用户身份
    userIdentity: storage.getUserIdentity(), //1 管理者 0 使用者
    teamList: [],
    clipRole: [],
    // 用户团队详情
    userTeamDetail: null,
    // 用户是否是主创权限
    power: 0,
    // 用户的页面权限列表
    powerList:[]
  },
  mutations: {
    SET_USER_IDENTITY: (state, userIdentity) => {
      state.userIdentity = userIdentity;
      storage.setUserIdentity(userIdentity);
    },
    SET_ORG_ID: (state, orgId) => {
      state.orgId = orgId;
      if(orgId>0){
        storage.setOrgId(orgId);
      }
    },
    SET_TEAM_ID: (state, teamId) => {
      state.teamId = teamId;
      if (teamId) {
        storage.setCurrentTeam(teamId);

        if(import.meta.env.ELECTRON){
          window.api.setTeamId(teamId);
        }
      } else {
        storage.clearCurrentTeam();
      }
    },
    SET_CONFIG_INFO: (state, configInfo) => {
      state.configInfo = configInfo;
      let iconLink = "";
      if (state.configInfo.basic) {
        iconLink =
          state.configInfo.basic.system_square_logo ||
          state.configInfo.basic.system_logo;
      }
      if (iconLink) {
        let $favicon = document.querySelector('link[rel="icon"]');
        if ($favicon !== null) {
          $favicon.href = iconLink;
        } else {
          $favicon = document.createElement("link");
          $favicon.rel = "icon";
          $favicon.href = iconLink;
          document.head.appendChild($favicon);
        }
      }
    },
    SET_TOKEN: (state, token) => {
      state.token = token;

      if (token) {
        storage.setToken(token);
      } else {
        storage.clearToken();
      }
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo;
      if (userInfo) {
        storage.setUserInfo(userInfo);
      } else {
        storage.clearUserInfo();
      }
    },
    SET_VILLAGE: (state, village) => {
      state.village = village;

      if (village) {
        storage.setVillageInfo(village);
      } else {
        storage.clearVillageInfo();
      }
    },
    SET_INVITE_CODE: (state, code) => {
      state.inviteCode = code;
      if (code) {
        localStorage.setItem("INVITE_CODE", code);
      } else {
        localStorage.removeItem("INVITE_CODE");
      }
    },

    SET_SCENE_TYPE: (state, code) => {
      state.inviteCode = code;
      if (code) {
        localStorage.setItem("SCENE_TYPE", code);
      } else {
        localStorage.removeItem("SCENE_TYPE");
      }
    },

    SET_UPLOAD_PATH: (state, code) => {
      state.upload_path = code;
      if (code) {
        localStorage.setItem("UPLOAD_PATH", code);
      } else {
        localStorage.removeItem("UPLOAD_PATH");
      }
    },

    SET_UPDATELIST: (state, info) => {
      state.updataList = info;
    },

    SET_DELUPDATA: (state, info) => {
      state.DelupData = info;
    },

    SET_COSPROGRESSLIST: (state, info) => {
      state.cos_progressList = info;
    },

    SET_UPLOADPROGRESS: (state, info) => {
      const existingItemIndex = state.uploadProgress.findIndex(
        (item) => item.filename === info.filename
      );

      if (existingItemIndex !== -1) {
        state.uploadProgress[existingItemIndex].uploadProgress =
          info.uploadProgress;
      } else {
        state.uploadProgress.push({
          filename: info.filename,
          uploadProgress: info.uploadProgress,
          upload_id: info.upload_id,
        });
      }
    },

    SET_UPLOADFAILED: (state, info) => {
      state.uploadfailed.push({
        filename: info.filename,
        isfailed: info.isfailed,
      });
    },

    SET_AI_CONFIG: (state, info) => {
      state.aiConfig = info;
    },
    SET_SCENE_APPS: (state, info) => {
      state.sceneApps = info;
    },
    SET_USER_ACCESS_SOURCE: (state, source) => {
      state.ua_source = source;
      storage.setUserAccessSource(source);
    },
    SET_MENU_PERMISSION: (state, menu_permission) => {
      state.menu_permission = menu_permission;
      storage.setMenuPermission(menu_permission);
    },
    SET_TEAM_LIST: (state, payload) => {
      state.teamList = payload;
    },
    SET_CLIP_ROLE: (state, payload) => {
      console.log(payload, 'clipRole 存放的值');
      
      state.clipRole = payload;
    },

    // 存放用户权限详情
    SET_USER_TEAM_DETAIL: (state, payload) => {
      state.userTeamDetail = payload;
      state.power = payload?.teamUser?.power??0
      state.powerList = payload?.teamUser?.team_user_role?.data?? []
    }
  },
  actions: {
    /**
     * @description: 设置org_id
     */
    SetOrgId({ commit }, orgId) {
      return new Promise((resolve) => {
        commit("SET_ORG_ID", orgId);
        commit("SET_TEAM_ID", storage.getCurrentTeam());
        commit("SET_TOKEN", storage.getToken());
        commit("SET_USER_INFO", storage.getUserInfo());
        commit("SET_VILLAGE", storage.getVillageInfo());
        resolve();
      });
    },
    SetTeamId({ commit }, teamId) {
      return new Promise((resolve) => {
        commit("SET_TEAM_ID", teamId);
        resolve();
      });
    },
    GetConfigInfo: ({ state, commit }, isRefresh = false) => {
      return new Promise((resolve, reject) => {
        if (state.configInfo && state.configInfo.basic && !isRefresh) {
          resolve(state.configInfo);
        } else {
          request
            .get("/public", "/system/config", { visitPort: "user" })
            .then((data) => {
              if (data?.code && data?.code != 1000) {
                reject()
                return
              }
              commit("SET_CONFIG_INFO", data);
              resolve(data);
            });
        }
      });
    },
    GetUserInfo: ({ state, commit }) => {
      // 先存放可能存在的 参数信息
      setConfige()
      return new Promise((resolve) => {
        if (state.userInfo) {
          resolve(state.userInfo);
          return;
        }

        if (utils.getUserToken()) {
        // if (state.token) {
          let params = {};
          let code = localStorage.getItem("INVITE_CODE");
          if (code) {
            params.code = code;
            localStorage.removeItem("INVITE_CODE");
          }
          let source = localStorage.getItem("USER_ACCESS_SOURCE");
          let sourceInfo = localStorage.getItem("USER_ACCESS_SOURCE_INFO");
          if (source) {
            params.source = source;
          }
          if (sourceInfo) {
            params.source_info = JSON.parse(sourceInfo);
          }
          request
            .post("/work_ai", "/user/info", { ...params })
            .then((userResult) => {
              commit("SET_TOKEN", userResult.user.user_token);
              commit("SET_USER_INFO", userResult.user);

              resolve(userResult.user);
            });
        } else {
          resolve();
        }
      });
    },
    GetVillageInfo: ({ state, commit }) => {
      return new Promise((resolve) => {
        if (state.village) {
          resolve(state.village);
          return;
        }

        request
          .get("/org", "/owner/ownerContractCityBuildList", {})
          .then((res) => {
            let currentVillage = null;

            if (res.list && res.list.length > 0 && res.list[0].villageList) {
              if (res.list[0].villageList.length > 0) {
                currentVillage = res.list[0].villageList[0];
                if (
                  res.list.length == 1 &&
                  res.list[0].villageList.length == 1
                ) {
                  currentVillage.oneVillage = true;
                } else {
                  currentVillage.oneVillage = false;
                }
                commit("SET_VILLAGE", currentVillage);
                resolve(currentVillage);
              } else {
                resolve(currentVillage);
              }
            } else {
              resolve(currentVillage);
            }
          });
      });
    },
    SetInviteCode({ commit }, code) {
      return new Promise((resolve) => {
        commit("SET_INVITE_CODE", code);
        resolve();
      });
    },

    SetScene_type({ commit }, code) {
      return new Promise((resolve) => {
        commit("SET_SCENE_TYPE", code);
        resolve();
      });
    },

    SetUploadPath({ commit }, code) {
      return new Promise((resolve) => {
        commit("SET_UPLOAD_PATH", code);
        resolve();
      });
    },

    

     SetCosProgresslist({ commit }, code) {
       return new Promise((resolve) => {
        commit("SET_COSPROGRESSLIST", code);
        resolve();
      });
    },

    uploadProgress({ commit }, code) {
      return new Promise((resolve) => {
        commit("SET_UPLOADPROGRESS", code);
        resolve();
      });
    },

    SetUpDateList({ commit }, code) {
      return new Promise((resolve) => {
        console.log('正在上传的内容??????', code);
        commit("SET_UPDATELIST", code);
        resolve();
      });
    },

    SetDelUpData({ commit }, code) {
      return new Promise((resolve) => {
        commit("SET_DELUPDATA", code);
        resolve();
      });
    },

    uploadfailed({ commit }, info) {
      return new Promise((resolve) => {
        commit("SET_UPLOADFAILED", info);
        resolve();
      });
    },
    SetAiConFig({ commit }, info) {
      return new Promise((resolve) => {
        commit("SET_AI_CONFIG", info);
        resolve();
      });
    },
    /**
     * @description: 登出
     */
    Logout({ commit, rootState }, info) {
      return new Promise(async (resolve) => {
        // 保留org_id
        let remember_me = localStorage.getItem("remember_me");
        let last_team = {
          last_team_id: utils.getCurrentTeam(),
          last_org_team: utils.getOrgId(),
        };
        let uid = "";
        const userInfo = await utils.getUserInfo();

        if (userInfo && userInfo.uid) {
          uid = userInfo.uid;
        }
        let org_id = utils.getOrgId();
        let itemsToPreserve = {};

        // 保留特定模式的键
        for (let i = 0; i < localStorage.length; i++) {
          const key = localStorage.key(i);

          if (key.includes("LASTORG_") && key.includes("_LASTUID_")) {
            itemsToPreserve[key] = localStorage.getItem(key);
          }
        }

        localStorage.clear();
        commit("SET_TOKEN", "");
        if (org_id) {
          commit("SET_ORG_ID", org_id);
        }
        if (remember_me) {
          localStorage.setItem("remember_me", remember_me);
        }

        Object.keys(itemsToPreserve).forEach((key) => {
          localStorage.setItem(key, itemsToPreserve[key]);
        });

        if (last_team.last_org_team && last_team.last_team_id && uid) {
          localStorage.setItem(
            "LASTORG_" + last_team.last_org_team + "_LASTUID_" + uid,
            last_team.last_team_id
          );
        }
        if (window.location.origin !== "https://v.kuaijing.cn") {
          router.push({ path: "/workShotstack/home" });
        } else {
          router.push({ path: "/workShotstack" });
        }
        resolve();
        // 刷新页面
        nextTick(() => {
          location.reload(true);
        });
      });
    },
    getAiConfig({ state, commit }) {
      let org_id = utils.getOrgId();
      if (org_id > 0) {
        return new Promise((resolve) => {
          if (!!state.aiConfig) {
            resolve(state.aiConfig);
          } else {
            request.get("/work_ai", "/config").then((res) => {
              if (res.list) {
                commit("SET_AI_CONFIG", res.list);
                resolve(res.list);
              } else {
                resolve();
              }
            });
          }
        });
      }
    },
    // 获取AI应用&&AI场景
    GetSceneApps({ state, commit }) {
      return new Promise((resolve) => {
        if (state.sceneApps.applicationList || state.sceneApps.industryList) {
          resolve(state.sceneApps);
        } else {
          request
            .get("/work_ai", "/application/industryCategory/list")
            .then((res) => {
              commit("SET_SCENE_APPS", res);
              resolve(res);
            });
        }
      });
    },
    SetUserAccessSource({ commit }, source) {
      return new Promise((resolve) => {
        commit("SET_USER_ACCESS_SOURCE", source);
        resolve();
      });
    },
    SetUserInfo({ commit }, info) {
      return new Promise((resolve) => {
        commit("SET_USER_INFO", info);
        resolve();
      });
    },
    GetTeamList: ({ state, commit }, payload) => {
      if (payload) {
        return new Promise((resolve) => {
          commit("SET_TEAM_LIST", payload);
          resolve(payload);
        });
      }
      return new Promise((resolve, reject) => {
        if (state.token) {
          request
            .get("/work_ai", "/user/team/list")
            .then((res) => {
              commit("SET_TEAM_LIST", res?.list);
              resolve(res);
            })
            .catch((err) => {
              reject(err);
            });
        } else {
          resolve();
        }
      });
    },
    SetClipRole({ commit }, info) {
      commit("SET_CLIP_ROLE", info);
    },
    GetClipRoleList({ commit }) {
      return new Promise((resolve) => {
        if (utils.isLogin()) {
          request.get("/work_ai", "/user/team/role/user").then((res) => {
            ensureTemplateListExists(res.result);
            commit("SET_CLIP_ROLE", res.result);
            resolve(res.result);
          });
        }

        function ensureTemplateListExists(items) {
          const keywords = new Set(["mbgc", "myTemplate"]);
          let templateListNeeded = false;
          let materialCenterExists = items.includes("MaterialCenter");

          // 检查是否需要添加TemplateList
          for (const item of items) {
            if (keywords.has(item)) {
              templateListNeeded = true;
              break;
            }
          }

          // 如果需要添加TemplateList，确保MaterialCenter也被添加
          if (templateListNeeded) {
            if (!materialCenterExists) {
              items.push("MaterialCenter"); // 添加MaterialCenter
            }
            // 确保TemplateList被添加到MaterialCenter之后
            const materialCenterIndex = items.indexOf("MaterialCenter");
            if (
              materialCenterIndex !== -1 &&
              !items.includes("TemplateList", materialCenterIndex)
            ) {
              items.splice(materialCenterIndex + 1, 0, "TemplateList"); // 在MaterialCenter之后添加TemplateList
            } else if (!items.includes("TemplateList")) {
              items.push("TemplateList"); // 如果MaterialCenter不存在，则直接添加TemplateList
            }
          }
        }
      });
    },

    // 获取用户权限详情
    getUserTeamDetail({ commit, state }) {
      return new Promise((resolve) => {
        if(state?.userTeamDetail) {
          resolve(state.userTeamDetail)
          return
        }
        if (utils.isLogin()) {
          request
           .get("/work_ai", "/user/team/detail", { id: storage.getCurrentTeam() })
            .then((res) => {
              commit("SET_USER_TEAM_DETAIL", res);
              resolve(res);
            });
        } else {
          resolve({});
        }
      });
    }

  },
};

export default user;
